pageLib={};
pageLib.api=function(paramObj){
	var defaultParamObj={
		action: '',
		data: null,
		type: null,
		success: null,
		failed: null,
		error: null
	};
	for(var key in defaultParamObj){
		paramObj[key]=paramObj[key] ? paramObj[key] : defaultParamObj[key];
	}
	// var apiBaseUrl="http://api.bybrain.cn";
	var apiBaseUrl="Api.php";
	var url=apiBaseUrl+paramObj.action;
	var requestType= !!paramObj.type ? paramObj.type : (paramObj.data ? "post" : "get");
	if(pageLib.getCookie('access-token')){
		if(paramObj.action.indexOf('?')>=0){
			url+='&access-token='+pageLib.getCookie('access-token');
		}
		else{
			url+='?access-token='+pageLib.getCookie('access-token');
		}
	}
	$.ajax({
		url:url,
		type: requestType,
		data: paramObj.data,
		dataType: "json",
		beforeSend: function(){
			pageLib.showIndicator();
		},
		complete: function(){
			pageLib.hideIndicator();
		},
		success:function(resp){
			if(resp.status==200&&resp.message==""){
				//success
				if(typeof paramObj.success==='function')paramObj.success(resp);
			}
			else{
				console.error(resp.message);
				// if(typeof paramObj.failed==='function')
				// 	paramObj.failed(resp);
				// else
				pageLib.alert(resp.message);
				if(typeof paramObj.failed==='function')paramObj.failed(resp);
			}
		},
		error: function(XMLHttpRequest,err,exeption){
			console.error(XMLHttpRequest.status);
			console.error(XMLHttpRequest.responseJSON.message);
			if(typeof paramObj.error==='function')paramObj.error(XMLHttpRequest,err,exeption);
		}
	});
};
pageLib.login=function(paramObj){
	/*
	paramObj={
		username: '',
		password: '',
		success: null,
		failed: null,
	};
	*/
	pageLib.api({
		action: '/v1/user/login',
		data: {
			username: paramObj.username,
			password: paramObj.password,
			login_type: "password_login",
			device_name: "mobileWeb"
		},
		success: function(resp){
			// console.log(data);
			pageLib.setCookie('access-token',resp.data.token,30);
			if(typeof paramObj.success==='function')paramObj.success(resp);
		},
		failed: function(resp){
			if(typeof paramObj.failed==='function')paramObj.failed(resp);
		}
	});
}
pageLib.logout=function(callback){
	pageLib.deleteCookie('access-token');
	pageLib.deleteCookie('balance');
	if(typeof callback==='function')callback();
}
pageLib.loadUserInfo=function(callback){
	pageLib.api({
		action: '/v1/user/get-user-info?t='+(new Date()).valueOf(),
		success: function(resp){
			var infobar=$('.user-info-bar');
			if(infobar.length>0){
				var availableBalance='￥'+(parseFloat(resp.data.balance)+parseFloat(resp.data.frozen_cash)+parseFloat(resp.data.red_cash)).toFixed(2);
				pageLib.setCookie('balance',(parseFloat(resp.data.balance)+parseFloat(resp.data.frozen_cash)+parseFloat(resp.data.red_cash)),null);
				infobar.show().find('.balance > div').eq(1).text(availableBalance);
				$('.login-bar').hide();
			}
			if(typeof callback==='function')callback(resp);
		},
		failed: function(resp){
			var infobar=$('.user-info-bar');
			if(infobar.length>0){
				$('.login-bar').show();
				infobar.hide();
			}
		}
	})
}
pageLib.submitOrder=function(order,callback){
	pageLib.api({
		action: '/v1/order/create-order',
		data: order.getClearOrderObject(),
		success: callback,
		failed: function(resp){
			console.error(resp.message);
		}
	});
}
pageLib.initAffiliate=function(){
	var affiliateId=pageLib.getCookie('affiliateId');
	if(!affiliateId){
		 afid=pageLib.getQueryArgs(window.location.href).afid;
		 if(/^[0-9]+$/.test(afid)){
		 	pageLib.setCookie('affiliateId',afid);
		 	return afid;
		 }
		 else{
		 	return null;
		 }
	}
	else{
		return affiliateId;
	}
}
pageLib.setCookie=function(cookieName,value,expireDays){
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expireDays)
	document.cookie=cookieName+ "=" +escape(value)+((expireDays==null) ? "" : ";expires="+exdate.toGMTString());
}
pageLib.getCookie=function(cookieName){
	var arr,reg=new RegExp("(^| )"+cookieName+"=([^;]*)(;|$)");
	if(arr=document.cookie.match(reg))
		return unescape(arr[2]);
	else
		return null;
}
pageLib.deleteCookie=function(cookieName){
	var exp = new Date();
	exp.setTime(exp.getTime() - 1);
	var cval=pageLib.getCookie(cookieName);
	if(cval!=null)
		document.cookie= cookieName + "="+cval+";expires="+exp.toGMTString();
}
pageLib.getQueryArgs=function(url){
	var args = {};
	var match = null;
	var search = decodeURIComponent(url.split('?')[1]);
	var reg = /(?:([^&]+)=([^&]+))/g;
	while((match = reg.exec(search))!==null){
		args[match[1]] = match[2];
	}
	return args;// Return the object
};
pageLib.copy=function(str){
	var save = function (e){
		e.clipboardData.setData('text/plain',str);//下面会说到clipboardData对象
		e.preventDefault();//阻止默认行为
	}
	document.addEventListener('copy',save);
	document.execCommand("copy");//使文档处于可编辑状态，否则无效
};
pageLib.showIndicator=function(){

};
pageLib.hideIndicator=function(){

};
pageLib.alert=function(msg){
	alert(msg);
}
pageLib.popup=function(html,callback,label){
	var popup= label != null ? document.getElementById(label) : document.getElementsByClassName('popupDialog');
	if((label == null && popup.length == 0) || (label != null && popup == null)){
		popup=document.createElement('div');
		if(label != null) popup.id = label;
		popup.className='popupDialog';
		document.body.appendChild(popup);
		if(html != null)
			popup.innerHTML=html;
	}else{
		if(!label)
			popup = popup[0];
	}
	setTimeout(function(){popup.className ='popupDialog animate-in';},200);
	if(typeof callback==='function'){
		
		var transitionEndEvent=['webkitTransitionEnd', 'transitionend', 'oTransitionEnd', 'MSTransitionEnd', 'msTransitionEnd'];
		for(var i=0;i<transitionEndEvent.length;i++){
			
			popup.removeEventListener(transitionEndEvent[i],function(e){
				callback(popup);
			});
			popup.addEventListener(transitionEndEvent[i],function(e){
				callback(popup);
			});
		}
	}
	return popup;
};
//关闭popup层(参数)
//parame.element	指定关闭的弹出层（可选省略则关闭当前页最后一个popup）
//parame.callback	回调函数（可选）
pageLib.closePopup=function(element,callback){
	if(typeof element==='function'){
		callback=element;
	}
	else if(element){
		popup=element;
	}
	var popupList=document.getElementsByClassName('popupDialog');
	var popup=document.getElementsByClassName('popupDialog').item(popupList.length-1);
	popup.className.replace('animate-in','');
	popup.className+=(' animate-out');
	var transitionEndEvent=['webkitTransitionEnd', 'transitionend', 'oTransitionEnd', 'MSTransitionEnd', 'msTransitionEnd'];
	for(var i=0;i<transitionEndEvent.length;i++){
		popup.addEventListener(transitionEndEvent[i],function(e){
			document.body.removeChild(popup);
			if(typeof callback==='function')callback();
		});
	}
};
